<template>
  <div :class="['notion-view', notionClick ? 'notion-click' : '']" id="notionview" @click="openNotion">
    <!-- <el-button class="upload-notion" type="primary">上传阅文意见</el-button> -->
    <div class="notion-item" v-for="(item) in notionData" :key="item.unid">
      <template v-if="!isLeftRight">
        <template v-if="showImageAndTextNotion">
          <div v-if="item.content == 'cldqy'">
            <el-image style="width:200px" fit="cover" v-if="cldqyImagePath" :src="cldqyImagePath"
              :preview-src-list="[cldqyImagePath]">
            </el-image>
          </div>
          <div style="line-height:1.5em;margin-bottom: 10px;" v-if="item.content != 'cldqy'"
            v-html="item.content && item.content.replace(/\n/g, '<br>').replace(/\t/g, '&emsp;')">
          </div>
          <div class="notion-image__wrapper" @click="handlePreviewImage(item.unid)"
            v-if="item.imagePath && item.fileType != 'pdf'">
            <el-image :id="'notion-image-' + item.unid" class="notion-image__image" fit="cover" :src="item.imagePath"
              :preview-src-list="[item.imagePath]">
            </el-image>
            <div class="print-btn" @click.stop="handlePrintImage(item)" v-if="showPrintYwyj">打印</div>
            <div class="print-btn" v-if="isEditLeaderNotion" @click.stop="handleDeleteFile(item)">删除</div>
          </div>
          <div class="notion-pdf__wrapper" @click.stop="handlePreviewPDF(item)" v-else-if="item.fileType">
            <el-image class="file-icon" src="/fileicon/PDF.png"> </el-image>
            <div>{{ item.fileName }}</div>
            <div class="print-btn" v-if="isEditLeaderNotion" @click.stop="handleDeleteFile(item)">删除</div>
          </div>

        </template>
        <template v-else-if="item.kind == '文字意见'">
          <div v-if="item.content == 'cldqy'">
            <el-image style="width:200px" fit="cover" v-if="cldqyImagePath" :src="cldqyImagePath"
              :preview-src-list="[cldqyImagePath]">
            </el-image>
          </div>
          <div v-else-if="item.content != 'cldqy'" style="line-height:1.5em;margin-bottom: 10px;"
            v-html="item.content && item.content.replace(/\n/g, '<br>').replace(/\t/g, '&emsp;')">
          </div>
        </template>
        <template v-else>
          <el-image style="width:200px" fit="cover" :src="item.imagePath" :preview-src-list="[item.imagePath]">
          </el-image>
        </template>
        <div class="rightContent" @contextmenu.prevent v-if="item.personList && !isFkxslksj">
          <div class="name" v-for="(personItem, index) in item.personList" :key="index">
            <template
              v-if="personItem.signaturePicture && personItem.xsdzqm == 1 && (!personItem.dzqmxsmk || (personItem.dzqmxsmk.indexOf('All') > -1 || personItem.dzqmxsmk.indexOf(moduleName) > -1))">
              <img @dragstart.prevent style="height:60px;object-fit: contain;margin-right:10px"
                :src="personItem.signaturePicture.indexOf('data') >= 0 ? personItem.signaturePicture : getOpenDownloadFile(personItem.signaturePicture)"
                alt="电子签名">
            </template>
          </div>
          {{ item.personList | getNotionInscribe(isConsignorFullname, getFormatdata(item.kind ==
            '文字意见'), item,moduleName,) }}
          <span title="修改意见" alt="修改意见" style="font-size:18px;margin-left:10px;" :style="{ color: themeColor }">
            <svg-icon v-if="showEditBtn(item)" @click="handleNotion(item)" icon-class="maobi" />
          </span>
        </div>

        <div class="rightContent" @contextmenu.prevent v-if="item.personList && isFkxslksj">
          <div class="name" style="margin-right:5px" v-for="(personItem, index) in item.personList" :key="index">
            <!-- 存在电子签名且显示电子签名 -->
            <template
              v-if="personItem.signaturePicture && personItem.xsdzqm == 1 && (!personItem.dzqmxsmk || (personItem.dzqmxsmk.indexOf('All') > -1 || personItem.dzqmxsmk.indexOf(moduleName) > -1))">
              <img @dragstart.prevent style="height:60px;object-fit: contain;margin-right:10px"
                :src="personItem.signaturePicture.indexOf('data') >= 0 ? personItem.signaturePicture : getOpenDownloadFile(personItem.signaturePicture)"
                alt="电子签名">
            </template>
            {{ [personItem] | getNotionInscribe(isConsignorFullname, getFormatdata(false), item, moduleName, index) }}
          </div>
          <span title="修改意见" alt="修改意见" style="font-size:18px;margin-left:10px;" :style="{ color: themeColor }">
            <svg-icon v-if="showEditBtn(item)" @click="handleNotion(item)" icon-class="maobi" />
          </span>
        </div>
      </template>
      <template v-else>
        <div class="left-right-wrapper">
          <div style="line-height:1.5em;margin-bottom: 10px;"
            v-html="item.content && item.content.replace(/\n/g, '<br>').replace(/\t/g, '&emsp;')">
          </div>
          <div class="rightContent" @contextmenu.prevent v-if="item.personList">
            <div class="name" style="margin-right:5px" v-for="(personItem, index) in item.personList" :key="index">
              <!-- 存在电子签名且显示电子签名 -->
              <template
                v-if="personItem.signaturePicture && personItem.xsdzqm == 1 && (!personItem.dzqmxsmk || (personItem.dzqmxsmk.indexOf('All') > -1 || personItem.dzqmxsmk.indexOf(moduleName) > -1))">
                <img @dragstart.prevent style="height:40px;object-fit: contain;margin-right:10px"
                  :src="personItem.signaturePicture.indexOf('data') >= 0 ? personItem.signaturePicture : getOpenDownloadFile(personItem.signaturePicture)"
                  alt="电子签名">
              </template>
            </div>
          </div>
        </div>
      </template>
    </div>
    <div class="signatrue-box" :id="type"></div>
    <!-- 上传阅文意见 -->
    <el-upload ref="YwyjUpload" class="upload-notion" action="" :before-upload="beforeUpload" v-if="isEditLeaderNotion"
      :auto-upload="false" :show-file-list="false" :on-change="handleFileChange">
      <div style="display:flex">
        <!-- @click="handleUploadYwyj" -->
        <el-button size="small" type="primary" :loading="uploading">上传阅文意见</el-button>
        <el-button size="small" type="primary" @click.stop="handleDqyj">代录阅文意见</el-button>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/pdf文件</div>
    </el-upload>
  </div>
</template>

<script>
import { writeNotionWithImage } from "../../api/common/flowsend";
import { getNotionList, changeYwjy, saveNotion, delNotion } from "../../api/common/notion";
import * as imageConversion from "image-conversion"
import { mapGetters, mapState } from "vuex";
import
{
  getListByPersonUnids
} from "../../api/module/systemPerson/systemPerson";
import showChoiceNotion from '../../components/choiceNotion';
import { getSxyjImageUrl, getOpenDownloadFile } from '../../api/common/attachment';
import { isArray } from '../../utils/validate';
import { isImgFile } from "hc-core/utils/index";
import showChoicePerson from "../../components/choicePerson/index";

//阅文意见回显
export default {
  name: "notionView",
  data()
  {
    return {
      //是否显示来源端
      isShowSourceClient: window.HC_config.VUE_YWYJ_SHOW_SOURCECLIENT || false,
      //共享意见是否分开显示落款时间
      isFkxslksj: window.HC_config.VUE_APP_GXYJKFXSLK || false,
      //图片和文字同时显示
      showImageAndTextNotion: false,
      //意见和签名左右布局显示
      isLeftRight: false,
      //使用显示部门
      isConsignorFullname: false,
      //阅文意见数据
      notionData: [],
      //必填提示内容
      requireMessage: "请上传领导意见",
      //标题
      modalTitle: "图片预览",
      confirmLoading: false,
      //显示图片
      popenevTVisible: false,
      //图片路径
      imageUrl: "",
      //阅文时间 字段
      readTime: "createTime",
      //人员详情
      personInfoObj: {},
      // 意见栏是否可点击
      notionClick: window.HC_config.VUE_APP_OPEN_FORMNOTION || false,
      //修改领导阅文意见
      editLeaderNotion: [],
      //流程节点信息
      nodeData: {},
      //选择委托人
      consignorIdent: '',
      //存在阅文意见
      hasNotion: [],
      //上传阅文意见
      uploading: false,
      //消息通道id
      channelId: new Date().getTime() + "" + Math.round(Math.random() * 1000),
      //消息通道
      channel: null,
      messageListener: null,
    };
  },
  props: {
    //数据项的unid
    unid: {
      type: String,
    },
    //类型
    type: {
      type: String,
    },
    //模块名
    moduleName: {
      type: String
    },
    //表单名
    formType: {
      type: String
    },
    //是否必填
    isRequire: {
      type: Boolean,
      default: false,
    },
    formatdata: {
      type: String,
      default: "%p% %o% %yyyy%-%MM%-%dd%"
    },
    //阅文意见列表
    notionList: {
      type: Array,
      default: () =>
      {
        return [];
      }
    },
    //只显示部门内意见
    isShowBmlNotion: {
      type: Boolean,
      default: false
    },
    //处理单圈阅列表
    cldqyList: {
      type: Array,
      default: () =>
      {
        return [];
      }
    },
  },
  computed: {
    ...mapGetters(["roleKey", "userInfo", "themeColor"]),
    ...mapState("user", ["ywyjxgSetting"]),
    //处理单圈阅路径
    cldqyImagePath()
    {
      if (this.cldqyList.length == 0)
      {
        return false;
      }
      console.error("处理单圈阅路径--------------->", this.cldqyList);
      return getOpenDownloadFile(this.cldqyList[0].filePath);
    },
    //是否显示修改领导阅文意见按钮 和 传图片阅文意见按钮
    isEditLeaderNotion()
    {
      //是否办结
      let stateZongJie = false;
      //是否是录入人
      let isNgrunid = false;
      if (this.nodeData)
      {

        stateZongJie = this.nodeData && (this.nodeData.state == 32 || this.nodeData.state == 8) ? true : false;

        isNgrunid = this.userInfo.unid == this.nodeData.ngrunid;
      }

      //参数配置 && 拟稿人
      return this.editLeaderNotion && this.editLeaderNotion.includes(this.type) && isNgrunid && !stateZongJie;
    },
    //显示打印阅文意见
    showPrintYwyj()
    {
      if (this.nodeData && this.nodeData.qx)
      {
        if (this.nodeData.qx.indexOf("总文书") > -1 || this.nodeData.qx.indexOf("档案员") > -1)
        {
          return true;
        }
      }
      return false;
    },
  },
  created()
  {
    this.initData();
    this.notionListHandler(this.notionList);
    console.log(this.formatdata, this.userInfo)
    console.log("流程节点", this.nodeData, '===', this.unid, this.type);
  },
  filters: {
    //获取阅文意见落款
    getNotionInscribe(P_PersonList, P_IsConsignorFullname, P_Format, P_Notion, P_ModuleName, P_Index, P_IsShowSourceClient)
    {
      let date = P_Notion.modifyTime;
      if (P_Index != null && P_Notion.shareOwnerTimes)
      {
        let timeArr = P_Notion.shareOwnerTimes.split(",");
        if (timeArr.length >= (P_Index + 1))
        {
          date = timeArr[P_Index];
        }
      }
      if (!date || !P_Format)
      {
        return '';
      }
      if (date.length == 6)
      {
        date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + "01";
      }
      if (date.length == 8)
      {
        date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
      }

      if (typeof date != "number")
      {
        date = date + '';
        if (date.indexOf("T") < 0)
        {
          date = date.replace(/-/g, '/')
        }
      }
      date = new Date(new Date(date).getTime());
      let personFullNameArr = [];
      if (P_IsConsignorFullname)
      {
        personFullNameArr = (P_Notion.consignorFullname && P_Notion.consignorFullname.split('/')) || [];
      } else
      {
        personFullNameArr = (P_Notion.ownerFullname && P_Notion.ownerFullname.split('/')) || [];
      }
      let ownerOrgFullname = "";
      let ownerOrgCommonName = "";
      if (personFullNameArr.length > 0)
      {
        personFullNameArr.shift();
        ownerOrgFullname = personFullNameArr.join("/");
        if (personFullNameArr.length > 0)
        {
          ownerOrgCommonName = personFullNameArr[0];
        }
      }
      let ownerCommonNameArr = [];
      let ownerFullnameArr = [];
      P_PersonList.forEach(per_personItem =>
      {
        //电子签名显示模块
        let dzqmxsmk = per_personItem.dzqmxsmk;
        let isShowDzqm = false;
        if (per_personItem.xsdzqm == 1)
        {
          if (dzqmxsmk)
          {
            let xsmkArr = dzqmxsmk.split(",");
            if (xsmkArr.indexOf("All") > -1 || xsmkArr.indexOf(P_ModuleName) > -1)
            {
              isShowDzqm = true;
            }
          }
          else
          {
            isShowDzqm = true;
          }
        }
        per_personItem.isShowDzqm = isShowDzqm;
        if (isShowDzqm && per_personItem.signaturePicture)
        {
          // ownerCommonNameArr.push("");
          // ownerFullnameArr.push("");
        }
        else
        {
          ownerCommonNameArr.push(per_personItem.personCommonname);
          ownerFullnameArr.push(per_personItem.personFullname);
        }
      })
      let ownerCommonName = ownerCommonNameArr.join("、");
      let ownerFullname = ownerFullnameArr.join("、");
      if (P_Notion.dlyj && !window.HC_config.VUE_APP_NOTSHOWDLBS)
      {
        ownerCommonName += "(代)"
        ownerFullname += "(代)"
      }

      let map = {
        M: date.getMonth() + 1,
        d: date.getDate(),
        h: parseInt(date.getHours()),
        m: date.getMinutes(),
        s: date.getSeconds(),
        p: ownerCommonName,
        P: ownerFullname,
        o: ownerOrgCommonName,
        O: ownerOrgFullname,
        q: Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds(), //毫秒
        r: P_Notion.remark || "",
        c: P_Notion.sourceClient ? "(来源：" + P_Notion.sourceClient + ")" : ""
      };
      P_Format = P_Format.replace(/((%y+%)|(%M+%)|(%d+%)|(%h+%)|(%m+%)|(%s+%)|(%q+%)|(%S+%)|(%o%)|(%p%)|(%O%)|(%P%)|(%r%)|(%c%))+/g, function (all, t)
      {
        t = t.replace(/%/g, "");
        all = all.replace(/%/g, "");
        let v = map[t[0]];
        if (v !== undefined)
        {
          if (all.length > 1)
          {
            v = '0' + v;
            v = v.substr(v.length - 2);
          }
          return v;
        } else if (t[0] === 'y')
        {
          return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
      });
      if (P_IsShowSourceClient && P_Notion.sourceClient != null)
      {
        P_Format = P_Format + "(来源：" + P_Notion.sourceClient + ")"
      }
      console.log(P_Format);
      return P_Format;
    },
    getFileName(P_Path)
    {
      if (!P_Path)
      {
        return;
      }
      P_Path = decodeURIComponent(P_Path);
      const split = P_Path.split("/");
      return split[split.length - 1];
    }
  },
  methods: {
    isImgFile,
    getOpenDownloadFile,
    //打印图片
    handlePrintImage(P_Item)
    {
      const img = new Image();
      img.crossOrigin = "Anonymous"; // 添加此行以支持 CORS
      img.src = P_Item.imagePath;
      console.log("打印图片", img.src);

      img.onload = () =>
      {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");

        canvas.width = img.width;
        canvas.height = img.height;

        context.drawImage(img, 0, 0);

        const printWindow = window.open("", "_blank");
        if (!printWindow)
        {
          console.error("无法打开新窗口");
          return;
        }

        printWindow.document.write(
          "<html><head><title>打印预览</title></head><body></body></html>"
        );

        const printImg = new Image();
        printImg.src = canvas.toDataURL();

        printImg.onload = () =>
        {
          printWindow.document.body.appendChild(printImg);
          printWindow.print();
          printWindow.close();
        };

        printImg.onerror = () =>
        {
          console.error("图片加载失败");
          printWindow.close();
        };
      };

      img.onerror = () =>
      {
        console.error("源图片加载失败");
      };
    },
    //删除文件阅文意见
    handleDeleteFile(P_Item)
    {
      //没有文字阅文意见直接删除
      if (!P_Item.content)
      {
        delNotion({ P_unids: P_Item.unid })
          .then(({ code }) =>
          {
            if (code == 200)
            {
              this.getNotionList(this.type);
              this.$message.success("删除成功");
            } else
            {
              this.$message.error("删除失败");
            }
          }).catch(res =>
          {
            this.$message.error("删除失败");
          })
      } else
      {
        //编辑
        P_Item.imagePath = "";
        P_Item.fileType = "";
        P_Item.flowstructureunid = this.nodeData.flowstructureunid;
        saveNotion(P_Item)
          .then(({ code }) =>
          {
            if (code == 200)
            {
              this.getNotionList(this.type);
              this.$message.success("删除成功");
            } else
            {
              this.$message.error("删除失败");
            }
          }).catch(err =>
          {
            this.$message.error("删除失败");
          });
      }
    },
    //更新流程节点信息
    updateNodeData(nodeData)
    {
      this.nodeData = nodeData;
      //console.log("更新流程节点数据", this.nodeData);
      this.initData();
    },
    initData()
    {
      //阅文意见左右布局
      if (window.HC_config.VUE_YWYJ_LEFT_RIGHT_LAYOUT && this.moduleName == 'htgl')
      {
        this.isLeftRight = true;
      }

      //代上传领导阅文意见
      if (window.HC_config.VUE_TWYJ_EDIT_LEADER_NOTION)
      {
        this.editLeaderNotion = window.HC_config.VUE_TWYJ_EDIT_LEADER_NOTION[this.moduleName] || [];
        if (!isArray(this.editLeaderNotion))
        {
          this.editLeaderNotion = this.editLeaderNotion[this.formType];
        }
        if (this.isEditLeaderNotion)
        {
          this.isConsignorFullname = true;
        }
      }
      //指定阅文意见类型 && 显示图片和文字
      if (this.editLeaderNotion && this.editLeaderNotion.includes(this.type) && window.HC_config.VUE_YWYJ_IMAGE_AND_TEXT_SHOW)
      {
        this.showImageAndTextNotion = true;
      }
    },
    //预览阅文意见图片
    handlePreviewImage(P_Unid)
    {
      const element = document.querySelector('#notion-image-' + P_Unid);
      if (element)
      {
        element.click()
      }
    },
    //pdf截图上传提示
    screenShotPDFConfirm()
    {
      return new Promise((resolve, _) =>
      {
        this.$confirm("此操作将替换已有图片阅文意见, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() =>
          {
            resolve(true);
          })
          .catch(e =>
          {
            resolve(false);
          })
      })
    },
    //预览PDF
    async handlePreviewPDF(P_Item)
    {
      this.screenShotPDFHandler(P_Item);
    },
    //获取落款 格式
    getFormatdata(P_IsTextYwyj)
    {
      // if (this.isEditLeaderNotion && !P_IsTextYwyj)
      // {
      //   return "%yyyy%-%MM%-%dd%";
      // }
      return this.formatdata;
    },
    //上传之前 文件验证
    async beforeUpload(file)
    {
      console.log("file.type", file.type);
      const isTP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'application/pdf';
      if (!isTP) 
      {
        this.$message.error('只能上传 PNG JPEG JPG PDF 格式!');
      }
      // const limitSize = window.HC_config.VUE_YWYJ_UPLOAD_FILE_SIZE;
      // if(limitSize){
      //   const isLt100M = file.size / 1024 / 1024 < limitSize
      //   if (!isLt100M) {
      //     this.$message.error(`文件不能大于 ${limitSize}MB!`)
      //     return false
      //   }
      // }
      return isTP;
    },
    //广播通道处理
    async broadcastChannelHandler(event)
    {
      const data = event.data;
      if (this.channelId == data.channelId)
      {
        if (this.hasNotion.includes('png') || this.hasNotion.includes('jpg') || this.hasNotion.includes('jpeg'))
        {
          const res = await this.screenShotPDFConfirm();
          if (!res)
          {
            return;
          }
        }
        const base64 = data.base64.split(',')[1];
        this.writeNotionWithImage(base64, "image/png");
      }
    },
    //截图pdf
    screenShotPDFHandler(P_Item)
    {
      if (!this.channel)
      {
        this.channel = new BroadcastChannel("notionPDF");
        this.messageListener = this.broadcastChannelHandler;
        // 监听广播通道的消息
        this.channel.addEventListener('message', this.messageListener);
      }
      window.open("/filepreview?url=" + encodeURIComponent(P_Item.imagePath) + "&channelId=" + this.channelId + "&fileType=pdf&fileName=" + encodeURIComponent(P_Item.fileName));
    },
    //选择文件
    async handleFileChange(file, fileList)
    {
      if (!this.beforeUpload(file.raw))
      {
        return;
      }
      let choicePerson = await showChoicePerson({ multiple: false });
      let wtrunid = null;
      if(choicePerson && choicePerson.choiceData)
      {
        wtrunid = choicePerson.choiceData.unid;
      }
      //console.log(file)
      this.file2Base64(file.raw, file.size).then(res =>
      {
        const base64 = res.split(',')[1];
        this.writeNotionWithImage(base64, file.raw.type,wtrunid);
      })
    },
    //文件转base64
    file2Base64(P_File, P_FileSize)
    {
      return new Promise(async (resolve, reject) =>
      {
        const limitSize = window.HC_config.VUE_YWYJ_UPLOAD_FILE_SIZE || 1024;
        if (P_FileSize > limitSize * 1024 && P_File.type.includes('image'))
        {
          //压缩的大小，可自定义 2000kb
          P_File = await imageConversion.compressAccurately(P_File, limitSize);
          console.log("压缩后的文件", P_File.size);
        }

        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(P_File);
        reader.onload = function ()
        {
          imgResult = reader.result;
        };
        reader.onerror = function (error)
        {
          reject(error);
        };
        reader.onloadend = function ()
        {
          resolve(imgResult);
        };
      });
    },
    //图片阅文意见
    writeNotionWithImage(base64, fileType,P_WtrUnid)
    {
      let notionParams = {
        docIdent: this.unid,
        notionContent: "",
        moduleName: this.moduleName,
        flowstructureunid: this.nodeData.flowstructureunid,
        sslb: "",
        published: 1,
        fileType: "",
        notionType: this.type,
        sourceClient: "网页端",
        wtrUnid: P_WtrUnid || this.userInfo.unid,
        isNew: true,
        file: base64,
      };
      if (fileType == "application/pdf")
      {
        if (this.hasNotion.includes('pdf'))
        {
          notionParams.isNew = false;
        }
        notionParams.fileType = 'pdf';
      } else
      {
        notionParams.fileType = fileType.split("/")[1];
        if (this.hasNotion.includes('png') || this.hasNotion.includes('jpg') || this.hasNotion.includes('jpeg'))
        {
          notionParams.isNew = false;
        }
      }
      notionParams.isNew = true;
      writeNotionWithImage(notionParams)
        .then(res =>
        {
          this.$message.success("上传阅文意见签写成功");
          this.getNotionList(this.type);
        })
        .catch(P_Error =>
        {
          console.error("[图片阅文意见接口异常]", P_Error);
          this.$message.error("上传阅文意见失败");
        });
    },
    //选择代录人
    handleChoiceBdqr(consignorIdent)
    {
      this.consignorIdent = consignorIdent;
      this.$refs.YwyjUpload.$refs["upload-inner"].handleClick();
    },
    //上传阅文意见
    handleUploadYwyj()
    {
      this.$refs.ChoiceBdqr.show({
        currentNotion: '',
        unid: this.unid,
        type: this.type,
        flowstructureunid: this.nodeData.flowstructureunid,
        notionId: '',
        moduleName: this.moduleName,
        formType: this.formType,
      })
    },
    //打开代签意见文
    handleDqyj()
    {
      showChoiceNotion({
        currentNotion: '',
        unid: this.unid,
        type: this.type,
        flowstructureunid: this.nodeData.flowstructureunid,
        notionId: '',
        content: '',
        moduleName: this.moduleName,
        formType: this.formType,
        isDqyj: true,
      }).then(res =>
      {
        this.getNotionList(this.type);
      })
    },
    // 打开阅文意见框
    openNotion()
    {
      if (window.HC_config.VUE_APP_OPEN_FORMNOTION)
      {
        showChoiceNotion({
          currentNotion: '',
          unid: this.unid,
          type: this.nodeData.notionType,
          flowstructureunid: this.nodeData.flowstructureunid,
          notionId: '',
          content: '',
          moduleName: this.moduleName,
          formType: this.formType
        }).then(res =>
        {
          this.getNotionList(this.nodeData.notionType);
        })
      }
    },
    //修改阅文意见
    handleNotion(p_Notion)
    {
      showChoiceNotion({
        currentNotion: p_Notion,
        unid: p_Notion.appIdent,
        type: p_Notion.type,
        notionId: p_Notion.unid,
        content: p_Notion.content,
        moduleName: this.moduleName,
        formType: this.formType
      }).then(res =>
      {
        this.getNotionList(p_Notion.type);
      })
    },
    //是否显示编辑按钮
    showEditBtn(notion)
    {
      let hasChangeNotion = false;
      if (this.ywyjxgSetting && this.ywyjxgSetting.bxgrunids)
      {
        let bgxrunidArr = this.ywyjxgSetting.bxgrunids.split(",");
        if (bgxrunidArr.indexOf(notion.ownerIdent) > -1)
        {
          console.log("阅文意见设置")
          return true
        }
      }
      if (this.nodeData)
      {
        if (this.nodeData.qx && this.nodeData.qx.indexOf("修改阅文意见") > -1)
        {
          //如果有权限 并且这条阅文意见是当前登录人所发则可修改
          if (notion.ownerIdent == this.$store.getters.userInfo.unid || this.isEditLeaderNotion)
          {
            return true;
          }
        }
      }
      return false;
    },
    //文件消息
    getFileInfo(imagePath)
    {
      const split = imagePath.split(".");
      const fileType = split.length > 1 ? split[1].toLowerCase() : "";

      let fileName = "";
      const splitFileName = imagePath.includes("\\") ? imagePath.split("\\") : imagePath.split("/");
      if (splitFileName.length > 1)
      {
        fileName = splitFileName[splitFileName.length - 1];
      }
      return { fileType, fileName };
    },
    //人员unid
    getPersonUnids(item)
    {
      let personUnids = "";
      if (window.HC_config.VUE_APP_NOTIONSHOWQSR)
      {
        //显示签署人
        personUnids = item.ownerIdent;
      }
      else
      {
        //显示委托人
        personUnids = item.consignorIdent || item.ownerIdent;
      }
      //存在共享意见
      if (item.shareOwnerIdents)
      {
        personUnids += "," + item.shareOwnerIdents;
      }
      return personUnids;
    },
    /**
     * 获取阅文意见数据
     *
     */
    notionListHandler(notionList)
    {
      this.notionData = [];
      this.hasNotion = [];
      notionList.forEach((item, index) =>
      {
        if (item.type != this.type)
        {
          return;
        }
        if (this.isShowBmlNotion && item.ownerOrgIdent != this.userInfo.orgUnid)
        {
          return;
        }

        if ((item.kind != "文字意见" && item.imagePath != null)
          || (this.showImageAndTextNotion && item.imagePath))
        {
          const fileInfo = this.getFileInfo(item.imagePath);
          item.fileType = fileInfo.fileType;
          item.fileName = fileInfo.fileName;
          item.imagePath = getSxyjImageUrl(item.imagePath);
        }
        if (item.ownerIdent == this.userInfo.unid)
        {
          this.hasNotion.push(item.fileType);
        }
        if (item.type == this.type)
        {
          this.notionData.push(item);
        }
        //有委托人 显示委托人 
        let personUnids = this.getPersonUnids(item);
        //获取人员详情信息
        if (personUnids != null && personUnids != "")
        {
          this.getListByPersonUnids(personUnids, item, this.notionData.length - 1)
        }
        else
        {
          item.personList = [{
            xsdzqm: 0, //不显示电子签名
            personCommonname: item.ownerFullname && item.ownerFullname.split("/")[0],
            personFullname: item.ownerFullname,
          }];
        }

      });
    },
    /**
     * 获取阅文意见数据
     * @param { String } P_Type 阅文意见类型
     */
    getNotionList(P_Type)
    {
      if (P_Type != this.type)
      {
        return;
      }
      getNotionList({
        appIdent: this.unid,
        type: this.type,
        pageNo: 1,
        pageSize: 1000,
      }).then(({ result }) =>
      {
        if (result)
        {
          let data = result.data || [];
          this.notionListHandler(data);
        }
      });
    },
    //获取用户详情已获取用户签名图片
    getListByPersonUnids(P_PersonUnids, P_NotionItem, P_Index)
    {
      // P_NotionItem.personList = [{
      //   unid: 1222,
      //   personCommonname: "简称",
      //   personFullName: "全称",
      //   xsdzqm: 1,
      // },
      // {
      //   unid: 1222,
      //   personCommonname: "简称1",
      //   personFullName: "全称1",
      //   xsdzqm: 1,
      // }]

      getListByPersonUnids({ unids: P_PersonUnids }).then(res =>
      {
        if (res.result.length >= 1)
        {
          P_NotionItem.personList = res.result;
        }
        else
        {
          P_NotionItem.personList = [{
            xsdzqm: 0, //不显示电子签名
            personCommonname: P_NotionItem.ownerFullname && P_NotionItem.ownerFullname.split("/")[0],
            personFullname: P_NotionItem.ownerFullname,
          }];
        }
        this.$set(this.notionData, P_Index, P_NotionItem)
      })
    }
  },
  beforeDestroy()
  {
    if (this.channel)
    {
      this.channel.removeEventListener("message", this.messageListener);
      this.channel.close();
    }
  }
};
</script>

<style lang="scss" scoped>
.notion-view {
  min-width: 200px;
  width: 100%;
  position: relative;
}

.notion-click {
  height: 100%;
  cursor: pointer;
}

.notion-item {
  padding: 5px 10px;
  display: flex;
  flex-direction: column;
  position: relative;

  .rightContent {
    align-self: flex-end;
  }

  &::after {
    content: "";
    position: absolute;
    width: 100%;
    left: 50%;
    top: -5px;
    transform: translateX(-50%);
    height: 1px;
    border-top: 1px dashed #ddd;
  }

  &:first-child {
    &::after {
      border-top: 0;
    }
  }
}

.rightContent {
  display: flex;
  align-items: center;

  .time {
    margin-left: 20px;
  }
}

.signatrue-box {
  position: absolute;
  right: 0;
  width: 200px;
  top: 0;
  height: 100%;
  z-index: -1;
}

.upload-notion {
  margin-left: 10px;
}

.el-upload__tip {
  margin-top: 10px;
  margin-top: 10px;
}

.notion-pdf__wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.notion-image__wrapper {
  height: 150px;
  // border: 1px solid #c0ccda;
  // border-radius: 6px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  cursor: pointer;

  .notion-image__image {
    height: 150px;
    width: 112px;
    margin: 0 10px;
  }

  &:hover {
    //background-color: #6e6c6c33;
  }
}

.print-btn {
  color: #409eff;
  cursor: pointer;
  margin-left: 10px;
}

.file-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

//意见和签名左右布局
.left-right-wrapper {
  display: flex;
  justify-content: space-between;
}
</style>